<template>
	<el-dialog title="按住此处可拖动"  v-loading="loading" v-model="props.moedelValue" width="360px" top="50vh" :show-close="false" @open="start" destroy-on-close :close-on-click-modal="false" :close-on-press-escape="false" draggable>

		<div class="content flex-column flex-aic">
			<div class="icon-wapper flex-center">
				<div class="icon-inner flex-center">
					<span class="iconfont icon-maikefeng maikefeng"></span>
				</div>
			</div>
			<div style="margin: 12px 0; color: #333333; font-size: 16px;">请开始说话</div>
			<div class="flex-aic">
				<!--录音音频可视化，波纹最大高度20px-->
				<img class="bolang" src="https://duomotai-1302957431.cos.ap-chongqing.myqcloud.com/icon/SketchPng80f4f556557f395cac4d8304edc04625b5758c9c7430d52c663586be4d7c2efb.gif" alt="">
				<div style="margin-left: 0.1rem">{{format_time}}</div>
			</div>
			<el-button type="primary" style="margin-top: 26px; width: 160px;" @click="end" :disabled="loading" v-loading="loading">结束回答</el-button>
		</div>

	</el-dialog>
</template>
<script setup>
import {defineProps, defineEmits, ref, onUnmounted, computed} from 'vue'
import { ElMessage } from 'element-plus'
import { useVideoRecorder } from '@/hooks/useVideoRecorder'
const props = defineProps({
	// 控制弹窗显示隐藏
	moedelValue: {
		type: Boolean,
		default: false
	},
  videoName: String,
  uploadFolder: String,
})

// 使用视频录制hooks
const { startRecording, stopAndUpload, cleanup} = useVideoRecorder({
  uploadFolder: props.uploadFolder,
  videoName: props.videoName
});

const emits = defineEmits(['update:modelValue', 'confirm'])

const loading = ref(false)

const timer = ref(null)
const recording_time = ref(0)
// 开始计时
const start_timer = () => {
	recording_time.value = 0
	timer.value = setInterval(() => {
		recording_time.value++
	}, 1000)
}

// 停止计时
const stop_timer = () => {
	if (timer.value) {
		clearInterval(timer.value)
		timer.value = null
	}
}

// 格式化时间显示
const format_time = computed(()=> {
  const mins = Math.floor(recording_time.value / 60)
  const secs = recording_time.value % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
})

const start = async ()=> {
  start_timer()
  await startRecording()
}
const end = async ()=> {
  if(recording_time.value < 10){
    ElMessage.warning('回答太短, 请至少录制10秒钟。')
    return;
  }
  stop_timer()
  try{
    loading.value = true
    await stopAndUpload()
    emits('confirm')
    emits('update:modelValue', false)
  }catch (e){
    ElMessage.error(e.message)
  }finally {
    loading.value = false
  }

}

// 组件销毁时清理资源
onUnmounted(() => {
  // 清理定时器
  stop_timer()
  // 清理视频录制相关资源
  if (cleanup) {
    cleanup()
  }
})


</script>

<style lang="scss" scoped>

.icon-wapper{
  width: .62rem;
  height: .62rem;
  border-radius: 50%;
  background: rgba(13, 140, 255, 0.50);
  .icon-inner{
    width: .44rem;
    height: .44rem;
    border-radius: 50%;
    background: #0D8CFF;
    .maikefeng{
      color: #fff;
      font-size: .32rem;
    }
  }
}
</style>
